package com.ktg.mes.chanjet.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.core.domain.TreeSelect;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.chanjet.entity.TpItemType;
import com.ktg.mes.chanjet.mapper.TpItemTypeMapper;
import com.ktg.mes.chanjet.service.TpItemTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class TpItemTypeServiceImpl extends ServiceImpl<TpItemTypeMapper,TpItemType> implements TpItemTypeService{


    @Autowired
    TpItemTypeMapper tpItemTypeMapper;

    @Override
    public List<TreeSelect> selectItemTypeList(TpItemType itemType) {
        List<TpItemType> tpItemTypes = buildTree(tpItemTypeMapper.selectItemTypeList(itemType));
        return tpItemTypes.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    private List<TpItemType> buildTree(List<TpItemType> itemTypes){
        List<TpItemType> returnList = new ArrayList<TpItemType>();
        List<Long> tempList = new ArrayList<Long>();
        for(TpItemType it : itemTypes){
            tempList.add(it.getId());
        }

        for(TpItemType it : itemTypes){
            if(!tempList.contains(it.getParentTypeId())){
                recursionFn(itemTypes,it);
                returnList.add(it);
            }
        }
        if(returnList.isEmpty()){
            returnList = itemTypes;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<TpItemType> list, TpItemType t)
    {
        // 得到子节点列表
        List<TpItemType> childList = getChildList(list, t);
        t.setChildren(childList);
        for (TpItemType tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<TpItemType> getChildList(List<TpItemType> list, TpItemType t)
    {
        List<TpItemType> tlist = new ArrayList<TpItemType>();
        Iterator<TpItemType> it = list.iterator();
        while (it.hasNext())
        {
            TpItemType n = (TpItemType) it.next();
            if (StringUtils.isNotNull(n.getParentTypeId()) && n.getParentTypeId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<TpItemType> list, TpItemType t)
    {
        return getChildList(list, t).size() > 0;
    }

}
